/**
 * 
 */
package com.couchcrowler.server.dao.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.couchcrowler.server.PMF;
import com.couchcrowler.server.dao.ProfileDao;
import com.couchcrowler.shared.Location;
import com.couchcrowler.shared.Profile;

/**
 * @author vienozin
 *
 */
public class ProfileDaoImpl implements ProfileDao {

	@Override
	public List<Profile> getProfiles(List<String> ids) {
		List<Profile> result = new ArrayList<Profile>(ids.size());
		for (String id : ids) {
			result.add(get(id));
		}

		return result;
	}

	@Override
	public void save(Profile profile) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(new ProfileWrapper(profile));
		} finally {
			pm.close();
		}		
	}
	
	@Override
	public Profile get(String id) {
		Profile result = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			result = pm.getObjectById(ProfileWrapper.class, id).getProfile();
		} catch (JDOObjectNotFoundException notFoundException) {
			/*
			 * Ignore and return null
			 */
		} finally {
			pm.close();
		}		
		
		return result;
	}
	
	@PersistenceCapable
	private static class ProfileWrapper {
		
		@PrimaryKey
		@Persistent
		private String id;
		
		@Persistent
		private String name;
		
		@Persistent
		private double longitude;
		
		@Persistent
		private double latitude;
		
		@Persistent
		private String pictureUrl;
		
		@Persistent
		private Set<String> contactsIds;
		
		@Persistent
		private boolean privateProfile;
		
		public ProfileWrapper(Profile profile) {
			id = profile.getId();
			
			name = profile.getName();
			pictureUrl = profile.getPictureUrl();
			
			contactsIds = profile.getContactsIds();
			privateProfile = profile.isPrivateProfile();

			if (profile.getLocation() != null) {
				longitude = profile.getLocation().getLongitude();
				latitude = profile.getLocation().getLatitude();
			}		
		}
		
		public Profile getProfile() {
			Profile result = new Profile();
			
			result.setId(id);
			result.setName(name);
			result.setPictureUrl(pictureUrl);
			result.setContactsIds(new HashSet<String>(contactsIds));
			result.setPrivateProfile(privateProfile);
			result.setLocation(new Location(longitude, latitude));
			
			return result;
		}
	}
}
